/*
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
    Given n = 3, your program should return all 5 unique BST's shown below.
   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
*/

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {
        vector<TreeNode *> trees;
        if (n < 1) trees.push_back(NULL);
        else trees= generateSubTrees(1, n);
        return trees;
    }
private:
    vector<TreeNode *> generateSubTrees(int left, int right) {
        vector<TreeNode *> res;
        for (int i = left; i <= right; i++) {
            vector<TreeNode *> ltrees, rtrees;
            if (i > left) ltrees = generateSubTrees(left, i-1);
            else ltrees.push_back(NULL);
            if (i < right) rtrees = generateSubTrees(i+1, right);
            else rtrees.push_back(NULL);
            for (auto it1 = ltrees.begin(); it1 != ltrees.end(); it1++) {
                for (auto it2 = rtrees.begin(); it2 != rtrees.end(); it2++) {
                    TreeNode *newtree = new TreeNode(i);
                    newtree->left = *it1;
                    newtree->right = *it2;
                    res.push_back(newtree);
                }
            }
        }
        return res;
    }
};
